package org.teachertools.web.struts;

import java.util.Enumeration;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.LookupDispatchAction;
import org.apache.struts.util.MessageResources;
import org.springframework.beans.factory.annotation.Configurable;
import org.teachertools.web.ServiceLocator;
import org.teachertools.web.SessionHelper;

@Configurable
public abstract class BaseDispatchAction extends LookupDispatchAction {

    public static final String SUCCESS = "success";
    public static final String ERROR = "error";
    public static final String MESSAGE = "MESSAGE";
    public static final String FLAG = "FLAG";
    public static final String TIMEOUT = "timeout";

    protected Logger logger = Logger.getLogger(getClass()); 
    
    @Resource
	private ServiceLocator serviceLocator;

	protected ServiceLocator getServiceLocator() {
		return serviceLocator;  
	}  

    protected String getMessage(HttpServletRequest request, String key) {
        MessageResources messageResources = (MessageResources) request.getAttribute(Globals.MESSAGES_KEY);
        return messageResources.getMessage(key);
    }

	@Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
        throws Exception {        
        String parameter = mapping.getParameter();
        if (parameter != null) {
          String name = request.getParameter(parameter);
          if (name == null) {
            return mapping.getInputForward();            
          }
        }

        return super.execute(mapping, form, request, response);
    }
    /**
     * This is the action called from the Struts framework when no parameter is specified.
     */
	@Override
    protected ActionForward unspecified(ActionMapping mapping, ActionForm form, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
        throws Exception {
        if (request.getSession().getAttribute(SessionHelper.IS_CONNECTED) == null) {
          ActionErrors errors = new ActionErrors();
          errors.add(ERROR, new ActionMessage("error.timeout"));
          saveMessages(request, errors);
          return mapping.findForward(TIMEOUT);
        }
        @SuppressWarnings("unchecked")
        Enumeration<String> enumeration = request.getAttributeNames();
        log.error("Dispatch Error - Request Content : ");
        while (enumeration.hasMoreElements())
        {
          String key = enumeration.nextElement();
          log.error("\t" + key + " = " + request.getAttribute(key));
        }
        throw new Exception("Unspecified dispatch parameter");
    }

	public ActionForward list(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        throw new Exception("Action \"list\" not implemented");
    }
    
    /**
     * This method forward to message.jsp 
     */
    public ActionForward forwardToMessage(ActionMapping mapping, HttpServletRequest request, String message, String flagvalue) {
        request.setAttribute(MESSAGE, message);
        request.setAttribute(FLAG, flagvalue);
        return mapping.findForward("message");
    }

    public ActionMessages getMessageListeResultat(List<?> liste) {
        ActionMessages actionMessages = new ActionMessages();

        if (liste != null) {
            if (liste.size() > 1) {
                actionMessages.add(
                        ActionMessages.GLOBAL_MESSAGE,
                        new ActionMessage("success.recordsselected",
                                String.valueOf(liste.size())));
            } else if (liste.size() == 1) {
                actionMessages.add(
                        ActionMessages.GLOBAL_MESSAGE,
                        new ActionMessage("success.recordselected", "1"));
            } else {
                actionMessages.add(
                        ActionMessages.GLOBAL_MESSAGE,
                        new ActionMessage("success.recordselected", "0"));
            }
        }

        return actionMessages;
    }
}
